package src.leetcode.everyday.mid_2982;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class maximumLength {
    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.maximumLength("accccerrrc"));
    }
}


class Solution {
    public int maximumLength(String s) {
        int ans = 0;
        for(int i = 0; i < 26; i++) {
            char c = (char) (i + 'a');

            List<Integer> counts = new ArrayList<Integer>();
            for(int j = 0; j < s.length();){
                int count = 0;
                while(j < s.length() && s.charAt(j++) == c) count++;
                if(count != 0) counts.add(count);
            }

            Collections.sort(counts, (a, b) -> b - a);
            for (int j = 0; j < counts.size() && j < 3; j++) {
                Integer num = counts.get(j);
                ans = Math.max(ans, num - (2 - j)); // 减去需要删除的
                if(j == 1 && counts.get(0) > counts.get(1)) ans = Math.max(ans, num);
            }
        }

        return ans > 0 ? ans : -1;
    }
}